package Management;

use Data::Dumper;
use Apache::Log;
use Apache::Constants qw( OK REDIRECT );
use Time::HiRes qw(gettimeofday);
use lib '/home/'.$ENV{HOSTUSER}.'/djpp/core/data';
use lib '/home/'.$ENV{HOSTUSER}.'/djpp/core/model';
use lib '/home/'.$ENV{HOSTUSER}.'/djpp/core/service';
use PreDefinedObjects;
use MiddleWare;
use Template;
use Request;  
use BaseUrls;

use Moose;

has settings 	=> ( is => 'ro' );
has request 	=> ( is => 'rw' );
has middle_ware	=> ( is => 'rw' );
has urls		=> ( is => 'rw' );
has template	=> ( is => 'rw' );

sub setup
{
	my $self = shift;
	
	$self->middle_ware( new MiddleWare( service =>  $self, classes => $self->settings->middle_ware ) );

	$self->urls( $self->settings->url_conf  );

	$self->template( new Template( path => $self->settings->template_dir ) );
}

sub handle_request
{
	my ($self, $r) = @_;
	
	my $log = $r->server->log; 

	my $t0 = gettimeofday;
	
	$self->request( new Request( realrequest => $r, service => $self ) );
	
	$log->warn("create request: ".(gettimeofday - $t0));
	my $t1 = gettimeofday;
	
	
	$self->{request} = $self->middle_ware->handle( $self->request );

	$log->warn("handle middleware: ".(gettimeofday - $t1));
	$t1 = gettimeofday;


	my $controller = $self->urls->handle( $self->request->uri );

	$log->warn("handle urls: ".(gettimeofday - $t1));
	$t1 = gettimeofday;
	
	my $response; 
	eval {
		$response = $controller->invoke($self->request);
	};
	if($@){
		warn Dumper("503",$@);
		$controller = PreDefinedObjects::get503Controller;
		$response = $controller->invoke($self->request);
	}

	$log->warn("invoke controller: ".(gettimeofday - $t1));
	$t1 = gettimeofday;
	if ( $response->cookie) {
		if (ref $response->cookie eq 'ARRAY'){
			for my $cookie (@{$response->cookie}){
				$cookie->set;
			}
		}
		else {
			$response->cookie->set;
		}
	}

	if ($response->redirect){
		$r->headers_out->set( location => $response->location );
		return REDIRECT;
	}
	
	$r->send_http_header( $response->type || 'text/html' );
	$r->print($response->html);

	$log->warn("send html: ".(gettimeofday - $t1));
	$t1 = gettimeofday;
	
	$log->warn("ALL REQUEST TIME: ".(gettimeofday - $t0));
	
	return OK;
}
1;
